<template>
  <!-- 下拉加多选框-->
  <el-select v-model="selectOptions" multiple placeholder="请选择" :popper-append-to-body="false" style="width:100%"
             @remove-tag="removeTag">
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
      <el-checkbox v-model="item.check" @change="isChecked(item)">{{ item.label }}</el-checkbox>
    </el-option>
    <div class="is-all">
      <div @click="selectAll(true)">全选</div>
      <div @click="selectAll(false)">反选</div>
    </div>
  </el-select>
</template>
<script setup lang="ts">

import {ref, watch} from "vue";

type SelectItem = {
  value: string | number,
  label: string,
  check: boolean
}
//接收的数据
const props = defineProps({
  options: {
    type: Array as () => SelectItem[],
    required: true,

  },
  width: {
    type: Number,
    default() {
      return 220;
    }
  },
  bindValue: {
    type: Array<string | number>,
    default() {
      return [];
    }
  }
})
//选择器宽度
//let selectWidth = "width:" + props.width + "px";
//注册事件，父组件可以调用
const emit = defineEmits(['selected'])
//下拉的数据
let selectOptions = ref<Array<string | number>>([])
//下拉点击事件
const isChecked = (item: SelectItem) => {
  if (item.check && selectOptions.value.indexOf(item.value) === -1) {
    selectOptions.value.push(item.value)
  } else if (!item.check) {
    selectOptions.value.forEach((value, index) => {
      if (value === item.value) {
        selectOptions.value.splice(index, 1);
      }
    })
  }
  emit('selected', selectOptions.value)
}
//删除图标的使用
const removeTag = (value: any) => {
  selectOptions.value.forEach((item, index) => {
    if (item === value) {
      selectOptions.value.splice(index, 1);
    }
  })
  emit('selected', selectOptions.value)
}
//全选和反选
const selectAll = (status: boolean) => {
  if (status) {
    selectOptions.value = []
    props.options.forEach((item: SelectItem) => {
      item.check = true;
      selectOptions.value.push(item.value)
    });
    console.log(selectOptions.value)
  } else {
    let arr: Array<string | number> = []
    props.options.forEach((item: SelectItem) => {
      item.check = false;
      if (!selectOptions.value.includes(item.value)) {
        arr.push(item.value)
      }
    });
    selectOptions.value = arr
  }

  emit('selected', selectOptions.value)
}
//清空数据
const clear = () => {
  selectOptions.value = []

}
//暴漏出去外部调用
defineExpose({
  clear
})
watch(
    () => props.bindValue,
    () => {
      selectOptions.value = props.bindValue;
      props.bindValue.forEach((item) => {
        props.options.find(dom => {
          if (dom.value == item) {
            dom.check = true
          }
        })
      })
    },
    {immediate: true}
)
</script>
<style scoped lang="scss">
.is-all {
  display: flex;
  padding: 10px;

  div {
    cursor: pointer;
    margin: 6px 10px;
    transition: 0.2s;

    &:hover {
      opacity: 0.7;
    }
  }

}
</style>